<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket的客户端</title>
<link href="layui/css/layui.css" rel="stylesheet" type="text/css" />
<script src="layui/layui.js"></script>
</head>
<body>
	<div class="layui-form-item">
		<h1>欢迎进入聊天页面：</h1>
	</div>

	<div class="layui-form-item">
		<h3><label class="layui-form-label">昵称：</label></h3>
		<div class="layui-input-inline" style="width: 180px;">
			<input type="text" id="userName" autocomplete="off"
				class="layui-input">
		</div>
		<input type="button" class="layui-btn" value="加入聊天室"
			onclick="joinChat()" />
	</div>

	<div class="layui-form-item">
		<h3><label class="layui-form-label">聊天框：</label></h3>
		<div class="layui-input-inline" style="width: 180px;">
			<input type="text" id="myText" autocomplete="off" class="layui-input" />
		</div>
		<input type="button" class="layui-btn" value="发送消息给服务端"
			onclick="sendMsg()" /> 
		<input type="button" class="layui-btn"
			value="退出聊天室" onclick="closeLink()" />
	</div>

	<div class="layui-form-item">
		<h1>消息列表：</h1>
	</div>
	<div id="showArea" class="layui-inline"></div>

	<script src="jquery-1.8.2.js"></script>
	<script>
		//声明一个websocket对象
		var websocket = null;
		function joinChat() {
			//获取输入框的值
			var userName = $("#userName").val();
			//声明一个请求地址，
			var url = "ws://localhost:8080/mywebsocket/" + userName;
			if (websocket == null) {
				//创建
				websocket = new WebSocket(url);
				//1.建立连接时触发
				websocket.onopen = function(event) {
					console.log("获取与服务端连接了");
					console.log(event);
				}
				//2.收到服务端的消息时触发
				websocket.onmessage = function(event) {
					console.log("接收到服务端的消息了");
					console.log("接收的消息是：" + event.data);
					$("#showArea").append("<p>" + event.data + "</p>");
					console.log(event);
				}
				//3.与服务端连接发生了异常
				websocket.onerror = function(event) {
					console.log("出现异常了");
				}
				//4.与服务端断开连接
				websocket.onclose = function(event) {
					console.log("连接关闭了");
				}
			}
		}

		//单击按钮时执行的函数,主动发送信息给服务端
		function sendMsg() {
			websocket.send($("#myText").val());
		}

		//单击按钮时执行的函数,主动关闭与服务端的连接
		function closeLink() {
			websocket.close();
		}
	</script>

</body>
</html>